package com.example.rdcproject.ving.notes.service;

import com.example.rdcproject.ving.notes.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.Set;

public class ClockIn {

    private Connection connection;

    private PreparedStatement statement;
    ConnectionPool connectionPool = ConnectionPool.getInstance();


    //创建实例化对象
   private  static  ClockIn instance = null;


   public static ClockIn getInstance(){
       if(instance == null){
           instance = new ClockIn();
       }
       return instance;
   }




    public int getContinousDays(String nickname) throws SQLException {
        String sql = "SELECT checkdate FROM checkin WHERE user_nickname = ? AND checkdate >= DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY checkdate ASC;";

        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,nickname);
        ResultSet resultSet = statement.executeQuery();

        int maxContinousDays = 0;
        int continousDays = 0;
        LocalDate lastDate = null;


        while (resultSet.next()) {
            LocalDate currentDate = resultSet.getDate("checkdate").toLocalDate();
            if (lastDate == null || lastDate.plusDays(1).equals(currentDate)) {
                continousDays++;
                if (continousDays > maxContinousDays) {
                    maxContinousDays = continousDays;


                }
            } else {
                continousDays = 1;
            }
            lastDate = currentDate;
        }

        return maxContinousDays;
    }





    public void  clockDates(String nickname) {
        DateTimeFormatter dateFormatter =  DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String today = LocalDate.now().format(dateFormatter);
        try {
            connection = connectionPool.getConnection();
            String sql = "INSERT INTO checkin (user_nickname, checkdate) VALUES (?, ?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,nickname);
            statement.setString(2, today);
            statement.executeUpdate();

            System.out.println("打卡成功");
            getContinousDays(nickname);

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("打卡失败");
        }
    }


    }


